'use strict';

angular.module('app')
    .controller('authManagerController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster', '$modal',
        function ($scope, $rootScope, $state, $timeout, toaster, $modal) {
            $scope.title = '授权管理';
            $scope.param = {};
            $scope.loading = false;

            $scope.search = function () {
                $scope.loading = true;
                if ($scope.pageFlag != 1) {//未点击翻页
                    $scope.param.pageNum = 1;//将页码设置为1，即跳转回第一页
                } else {//点击翻页
                    $scope.pageFlag = 2;//将开关值设置为2
                }
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    url: 'dac/authm/cardAuth/list',
                    data: angular.toJson($scope.param)
                }).then(function (result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        $scope.pageInfo = result;
                        console.log(result)
                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                    var userId = localStorage.getItem('userId');
					var strIds = getCookie(userId+"1");
					if(strIds===null){
						return;
					}
					var ids = strIds.split(",");
					for(var i=0;i<ids.length;i++){
					var id = ids[i];
					var object = document.getElementById(id);
					if(object!=null){
						object.checked = true;
					}
				}
				var checkBoxs = $(".tbody input[name='Fruit']").length;//单选框的个数
                var checkeds = $(".tbody input[name='Fruit']:checked").length//单选框选中的个数
                var checkBoxss = $(".tbody input[name='Fruit']");
                $("#allCheck").prop("checked",checkBoxs === checkeds ? true : false);//个数与选中个数相同时，全选按钮选中，否则不选中
                });
            }
            


            //从本地获取localstorage数据，对权限按钮做隐藏
            var personAuth = localStorage.getItem("PersonAuth");//获取PersonAuth的值
            personAuth = personAuth.split(',');
            for (var i = 0; i < personAuth.length; i++) {
                if (personAuth[i] == 'main.authm.cardAuth.read') {
                    $scope.read = true;
                }
                if (personAuth[i] == 'main.authm.cardAuth.add') {
                    $scope.add = true;
                }
                if (personAuth[i] == 'main.authm.cardAuth.update') {
                    $scope.update = true;
                }
                if (personAuth[i] == 'main.authm.cardAuth.delete') {
                    $scope.dele = true;
                }
            }
            
            //全选按钮
            $scope.allCheck = function($event){
                var allcheck = $event.target ;//全选按钮
                var checked = allcheck.checked ;//选中状态
                var checkBoxs = $(".tbody input[name='Fruit']");
                checkBoxs.each(function(i){
                    this.checked = checked;
                    $scope.saveIdOrRemoveId(this);
                });
            }

 			//检测没有全选就将全选按钮变为未选状态
            $scope.checkStatus = function () {
                var checkBoxs = $(".tbody input[name='Fruit']").length;//单选框的个数
                var checkeds = $(".tbody input[name='Fruit']:checked").length//单选框选中的个数
                var checkBoxss = $(".tbody input[name='Fruit']");
                checkBoxss.each(function(i){
                    $scope.saveIdOrRemoveId(this);
                });
                $("#allCheck").prop("checked",checkBoxs === checkeds ? true : false);//个数与选中个数相同时，全选按钮选中，否则不选中
            }
			
			//存储被勾选中的id或者删除取消勾选的id
			$scope.saveIdOrRemoveId = function(check){
				var userId = localStorage.getItem('userId');
				var OldIds = getCookie(userId+"1");;
				if(OldIds===null){
					OldIds = "";
				}
				var checked = check.checked ; //当前行勾选按钮的状态
				if(checked){
					OldIds +=  check.value+",";
					setCookie(userId+"1",OldIds,'h1');
					return;
					}
				var strs= new Array(); //定义一数组 
				strs=OldIds.split(","); //字符分割
				var newIds = "";
				for(var i=0;i<strs.length;i++){
					if(strs[i]===check.value||strs[i]===""){
						setCookie(userId+"1",newIds,'h1');
						continue;
					}
					newIds += strs[i]+",";
					setCookie(userId+"1",newIds,'h1');
				}
				
			}
			
            $scope.search();

            $scope.clearSearch = function () {
                $scope.param.keyword = null;
                $scope.search();
            }

            $scope.disableItem = function (id, enable) {

            }

            $scope.delAuth = function (authNo) {
                debugger

//			$scope.search();
                $scope.delParam = {};
                $scope.delParam.authNo = authNo;
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    url: 'dac/authm/cardAuth/delAuth',
                    data: angular.toJson($scope.delParam)
                }).then(function(result){
                    if (result.httpCode == 200) {//成功
                        toaster.clear('*');
                        toaster.pop('success', '', "保存成功");
                        $timeout(function () {
                            $state.go('main.authm.cardAuth.list', null, {
                                reload: true
                            });
                        }, 1000);
                    } else {
                        toaster.clear('*');
                        toaster.pop('error', '', result.msg);
                        $scope.isDisabled = false;
                    }
                });

            }

            // 翻页
            $scope.pagination = function (page) {
                $scope.param.pageNum = page;
                $scope.pageFlag = 1;//将开关值设置为1
                $scope.search();
            };
            
            $scope.delAll = function(){
			var userId = localStorage.getItem('userId');
				var ids = getCookie(userId+"1");;
				delCookies(userId+"1");
		  var checkeds = ids.split(",")//单选框选中的个数
                if(checkeds.length === 1 ){
                alert('最小选中一个');
                return;
                }
                $scope.openDelAuth(ids);
		}

            $scope.openDelAuth = function (delId) {
                var modalInstance = $modal.open({
                    templateUrl: 'delAuth.html',//script标签中定义的id
                    controller: 'delAuthModalCtrl',//modal对应的Controller
                    resolve: {
                        delId: function () {
                            return delId;
                        }
                    }
                });
            };
            
           //读取cookies
           function getCookie(name){
           	  var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
				if(arr=document.cookie.match(reg))
				return unescape(arr[2]);
				else
				return null;
           }
           
           //删除cookies
           function delCookies(name){
           	 var exp = new Date();
			 exp.setTime(exp.getTime() - 1);
				var cval=getCookie(name);
				if(cval!=null)
			document.cookie= name + "="+cval+";expires="+exp.toGMTString();
           }
            
            //设置cookies
			//如果需要设定自定义过期时间
			//那么把上面的setCookie　函数换成下面两个函数就ok;
			//程序代码
			function setCookie(name,value,time)
			{
			var strsec = getsec(time);
			var exp = new Date();
			exp.setTime(exp.getTime() + strsec*1);
			document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
			}
			function getsec(str)
			{
			var str1=str.substring(1,str.length)*1;
			var str2=str.substring(0,1);
			if (str2=="s")
			{
			return str1*1000;
			}
			else if (str2=="h")
			{
			return str1*60*60*1000;
			}
			else if (str2=="d")
			{
			return str1*24*60*60*1000;
			}
			}
			//这是有设定过期时间的使用示例：
			//s20是代表20秒
			//h是指小时，如12小时则是：h12
			//d是天数，30天则：d30
            
        }]);

app.controller('delAuthModalCtrl', function ($scope, $rootScope, $modal, $modalInstance, $state, $timeout, delId) {


    $scope.delAuth = function () {
        var del = $scope.isDelAll + "";
        var isDelAll = 0;
        if (del == "true")
            isDelAll = 1;
        $modalInstance.close();
        $scope.delParam = {};
        $scope.delParam.id = delId;
        $scope.delParam.isDelAll = isDelAll;
		$scope
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: 'dac/authm/cardAuth/delAuth',
            data: angular.toJson($scope.delParam)
        }).then(function(result){
            if (result.httpCode == 200) {//成功
                alert('销卡成功');
                $timeout(function () {
                    $state.go('main.authm.cardAuth.list', null, {
                        reload: true
                    });
                }, 1000);
            } else {
                alert(result.msg);
                $scope.isDisabled = false;
            }
        });

    }

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };

});